<template>
  <div class="container-fluid p-4">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="d-flex align-items-center">
            <i class="bi bi-people-fill stat-icon text-primary"></i>
            <div>
              <div class="stat-label">我的学生总数</div>
              <div class="stat-value">{{ totalUsers }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="d-flex align-items-center">
            <i class="bi bi-person-check-fill stat-icon text-success"></i>
            <div>
              <div class="stat-label">活跃学生</div>
              <div class="stat-value">{{ activeUsers }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="d-flex align-items-center">
            <i class="bi bi-person-plus-fill stat-icon text-warning"></i>
            <div>
              <div class="stat-label">新增学生 (本月)</div>
              <div class="stat-value">{{ newUsersMonth }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="d-flex align-items-center">
            <i class="bi bi-person-dash-fill stat-icon text-danger"></i>
            <div>
              <div class="stat-label">待审核学生</div>
              <div class="stat-value">{{ pendingUsers }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮和搜索 -->
    <el-card class="mb-4" shadow="never">
      <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
          <el-button type="primary" :icon="Plus" @click="handleCreateUser"
            >添加学生</el-button
          >
          <el-button type="success" :icon="Upload" @click="handleBatchImport"
            >批量导入</el-button
          >
        </div>
        <el-input
          v-model="searchQuery"
          placeholder="搜索学生姓名、学号..."
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch"></el-button>
          </template>
        </el-input>
      </div>

      <!-- 筛选条件 -->
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="选择状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="活跃" value="active"></el-option>
            <el-option label="禁用" value="inactive"></el-option>
            <el-option label="待审核" value="pending"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="filterForm.registrationDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="applyFilters">筛选</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h5>学生列表</h5>
        </div>
      </template>
      <el-table :data="paginatedUsers" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="username" label="学生姓名"></el-table-column>
        <el-table-column prop="studentId" label="学号"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{
              getStatusText(scope.row.status)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registrationDate" label="注册日期" width="180"></el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              :type="scope.row.status === 'active' ? 'warning' : 'success'"
              @click="toggleUserStatus(scope.row)"
              >{{
                scope.row.status === "active" ? "禁用" : "启用"
              }}</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalFilteredUsers"
        layout="prev, pager, next"
        background
        class="mt-4 justify-content-center"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Plus, Upload } from "@element-plus/icons-vue";

const searchQuery = ref("");
const filterForm = reactive({
  status: "",
  registrationDate: null,
});

const users = ref([
  {
    id: 1,
    username: "张小明",
    studentId: "S001",
    email: "zhangxm@example.com",
    status: "active",
    registrationDate: "2023-01-01",
  },
  {
    id: 2,
    username: "李红",
    studentId: "S002",
    email: "lih@example.com",
    status: "inactive",
    registrationDate: "2023-01-15",
  },
  {
    id: 3,
    username: "王刚",
    studentId: "S003",
    email: "wangang@example.com",
    status: "pending",
    registrationDate: "2023-02-01",
  },
  {
    id: 4,
    username: "赵丽",
    studentId: "S004",
    email: "zhaoli@example.com",
    status: "active",
    registrationDate: "2023-02-10",
  },
  {
    id: 5,
    username: "钱多多",
    studentId: "S005",
    email: "qiandd@example.com",
    status: "active",
    registrationDate: "2023-03-01",
  },
]);

const currentPage = ref(1);
const pageSize = ref(10);

const totalUsers = computed(() => users.value.length);
const activeUsers = computed(
  () => users.value.filter((user) => user.status === "active").length
);
const newUsersMonth = computed(() => {
  const now = new Date();
  const currentMonth = now.getMonth();
  const currentYear = now.getFullYear();
  return users.value.filter((user) => {
    const regDate = new Date(user.registrationDate);
    return (
      regDate.getMonth() === currentMonth &&
      regDate.getFullYear() === currentYear
    );
  }).length;
});
const pendingUsers = computed(
  () => users.value.filter((user) => user.status === "pending").length
);

const filteredUsers = computed(() => {
  let filtered = users.value;

  // Search query
  if (searchQuery.value) {
    filtered = filtered.filter(
      (user) =>
        user.username.includes(searchQuery.value) ||
        user.studentId.includes(searchQuery.value)
    );
  }

  // Filters
  if (filterForm.status) {
    filtered = filtered.filter((user) => user.status === filterForm.status);
  }
  if (filterForm.registrationDate && filterForm.registrationDate.length === 2) {
    const [start, end] = filterForm.registrationDate;
    filtered = filtered.filter((user) => {
      const regDate = new Date(user.registrationDate);
      return regDate >= start && regDate <= end;
    });
  }

  return filtered;
});

const totalFilteredUsers = computed(() => filteredUsers.value.length);

const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredUsers.value.slice(start, end);
});

const getStatusType = (status) => {
  switch (status) {
    case "active":
      return "success";
    case "inactive":
      return "danger";
    case "pending":
      return "warning";
    default:
      return "info";
  }
};

const getStatusText = (status) => {
  switch (status) {
    case "active":
      return "活跃";
    case "inactive":
      return "禁用";
    case "pending":
      return "待审核";
    default:
      return "未知";
  }
};

const handleSearch = () => {
  currentPage.value = 1;
  // In a real application, you would fetch data from the backend here
  console.log("执行搜索:", searchQuery.value);
};

const applyFilters = () => {
  currentPage.value = 1;
  // In a real application, you would fetch data from the backend here
  console.log("应用筛选:", filterForm);
};

const resetFilters = () => {
  searchQuery.value = "";
  filterForm.status = "";
  filterForm.registrationDate = null;
  currentPage.value = 1;
  // In a real application, you would re-fetch data from the backend here
};

const handleCreateUser = () => {
  ElMessage.info("添加学生功能待实现");
  // Implement create user logic, e.g., open a dialog
};

const handleBatchImport = () => {
  ElMessage.info("批量导入功能待实现");
  // Implement batch import logic, e.g., open a file upload dialog
};

const handleEdit = (row) => {
  ElMessage.info(`编辑学生: ${row.username}`);
  // Implement edit logic, e.g., open a dialog with row data
};

const toggleUserStatus = (row) => {
  const newStatus = row.status === "active" ? "inactive" : "active";
  ElMessageBox.confirm(
    `确定要${newStatus === "active" ? "启用" : "禁用"}学生 "${
      row.username
    }" 吗？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      row.status = newStatus;
      ElMessage.success(
        `${newStatus === "active" ? "启用" : "禁用"}成功!`
      );
    })
    .catch(() => {
      ElMessage.info("已取消操作");
    });
};

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除学生 "${row.username}" 吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      users.value = users.value.filter((user) => user.id !== row.id);
      ElMessage.success("删除成功!");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  console.log("每页条数:", newSize);
};

const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  console.log("当前页码:", newPage);
};
</script>

<style scoped>
/* 卡片头部样式 */
.card-header {
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}

/* 统计卡片样式 */
.stat-card {
  margin-bottom: 20px;
}

.stat-card .el-card__body {
  padding: 16px;
}

.stat-card .stat-icon {
  font-size: 24px;
  margin-right: 8px;
}

.stat-card .stat-value {
  font-size: 24px;
  font-weight: bold;
  margin: 8px 0 4px;
}

.stat-card .stat-label {
  color: var(--el-text-color-secondary);
  font-size: 12px;
}

/* 筛选表单样式 */
.filter-form {
  padding: 16px;
}

.filter-form .el-form-item {
  margin-bottom: 0;
}

/* 表格样式 */
.el-table {
  margin-top: 0;
}

/* 操作按钮样式 */
.action-buttons .el-button {
  margin-right: 8px;
}

/* 分页样式 */
.el-pagination {
  margin-top: 16px;
  justify-content: flex-end;
}

/* 兼容 Bootstrap Icons */
.bi {
  vertical-align: -0.125em;
}
</style>